<template>
  <div class="departments-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="组织架构" name="first" />
    </el-tabs>
    <el-card class="tree-card">
      <!-- 用了一个行列布局 -->
      <el-row
        type="flex"
        justify="space-between"
        align="middle"
        style="height: 40px"
        class="card-title"
      >
        <el-col>
          <svg-icon icon-class="company" /><span class="title">{{
            companyName
          }}</span>
        </el-col>
        <el-col :span="4">
          <el-row type="flex" justify="end">
            <!-- 两个内容 -->
            <el-col>负责人</el-col>
            <el-col>
              <!-- 下拉菜单 element -->
              <el-dropdown>
                <span> 操作<i class="el-icon-arrow-down" /> </span>
                <!-- 下拉菜单 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item><el-button
                    type="text"
                    @click="showDialog('')"
                  >添加部门</el-button></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-divider />
      <!-- //:props="defaultProps" -->
      <el-tree v-loading="loading" :data="departs">
        <el-row
          slot-scope="{ data }"
          type="flex"
          justify="space-between"
          align="middle"
          style="height: 40px"
          class="card-title"
        >
          <el-col>
            <span
              class="title"
            ><svg-icon
               v-if="!(data.children && data.children.length)"
               icon-class="department"
             />
              {{ data.name }}</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>{{ data.manager }}</el-col>
              <el-col>
                <!-- 下拉菜单 element -->
                <el-dropdown>
                  <span> 操作<i class="el-icon-arrow-down" /> </span>
                  <!-- 下拉菜单 -->
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item><el-button
                      type="text"
                      @click="showDialog(data.id)"
                    >添加子部门</el-button></el-dropdown-item>
                    <el-dropdown-item><el-button
                      type="text"
                      @click="getDeparById(data.id)"
                    >查看部门</el-button></el-dropdown-item>
                    <el-dropdown-item><el-button
                      type="text"
                      @click="delDepar(data.id)"
                    >删除部门</el-button></el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-tree>
    </el-card>
    <el-dialog
      :title="title"
      show-close
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="isdhow"
      @closed="closeDialog"
    >
      <el-form
        ref="departmentForm"
        :model="departmentForm"
        :rules="departmentRules"
      >
        <el-form-item
          label="部门名称"
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input v-model="departmentForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门编码"
          prop="code"
          :label-width="formLabelWidth"
        >
          <el-input v-model="departmentForm.code" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门负责人"
          prop="manager"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="departmentForm.manager"
            placeholder="请选择"
            @focus="getEmployee"
          >
            <el-option
              v-for="item in employeeList"
              :key="item.id"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门介绍"
          prop="introduce"
          :label-width="formLabelWidth"
        >
          <el-input v-model="departmentForm.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartmentById,
  getDepartmentList,
  addDepartments,
  delDepartments,
  updDepartments
} from '@/api/department'
import { getEmployeeSimple } from '@/api/employee'
import { fromData } from '@/utils/index'
export default {
  name: 'Departments',
  data() {
    return {
      isdhow: false,
      activeName: 'first',
      companyName: '',
      loading: false,
      // 组织架构列表
      departs: [],
      dialogFormVisible: false,
      // 部门表单
      departmentForm: {
        name: '',
        manager: '',
        code: '',
        introduce: '',
        pid: ''
      },
      formLabelWidth: '120px',
      // 管理员列表
      employeeList: [],
      // 校验验证
      departmentRules: {
        name: [
          { required: true, trigger: 'blur', message: '部门名称不能为空' },
          {
            min: 1,
            max: 10,
            message: '部门名称要求1-10个字符',
            trigger: 'blur'
          },
          {
            validator: async(rule, value, callback) => {
              const res = await getDepartmentList()
              const checkRes = res.depts.some(v => {
                if (this.departmentForm.id) {
                  // 编辑
                  if (value === v.name && this.departmentForm.id !== v.id) {
                    return true
                  }
                } else {
                  return value === v.value
                }
              })
              checkRes === true
                ? callback(new Error('部门名称已存在,请重新输入!'))
                : callback()
              // some简写,只要有一个条件满足就返回true
              // !res.depts.some(v => value === v.name)
              //   ? callback()
              //   : callback(new Error('部门名称已存在,请重新输入!'))

              // res.depts.filter(v =>value === v.name).length===0
              //  ? callback()
              //   : callback(new Error('部门名称已存在,请重新输入!'))
            },
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, trigger: 'change', message: '请选择管理员' }
        ],
        code: [
          { required: true, trigger: 'blur', message: '部门编码不能为空' },
          {
            min: 1,
            max: 10,
            trigger: 'blur',
            message: '部门编号要求1-10个字符'
          },
          {
            validator: async(rule, value, callback) => {
              const res = await getDepartmentList()
              const checkRes = res.depts.some(v => {
                if (this.departmentForm.id) {
                  // 编辑
                  if (value === v.code && this.departmentForm.id !== v.id) {
                    return true
                  }
                } else {
                  return value === v.code
                }
              })
              checkRes === true
                ? callback(new Error('部门编号已存在,请重新输入!'))
                : callback()
              //   res.depts.filter(v => value === v.code).length === 0
              //     ? callback()
              //     : callback(new Error('部门名称已存在,请重新输入!'))
              // },
              ;('blur')
            }
          }
        ],
        introduce: [
          { required: true, trigger: 'blur', message: '部门介绍不能为空' },
          {
            min: 1,
            max: 50,
            trigger: 'blur',
            message: '部门介绍要求1-50个字符'
          }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.departmentForm.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 获得组织架构
    async getDepartment() {
      this.loading = true
      const res = await getDepartmentList()
      this.companyName = res.companyName
      const rootTree = fromData(res.depts, '')
      this.departs = rootTree
      setTimeout(() => {
        this.loading = false
      }, 300)
    },
    // 1绑定下拉列
    async getEmployee() {
      const res = await getEmployeeSimple()
      this.employeeList = res
    },
    // 添加部门的点击事件
    showDialog(pid) {
      console.log(pid)
      this.departmentForm.pid = pid
      this.dialogFormVisible = true
    },
    // 弹窗关闭时的回调函数
    closeDialog() {
      this.$refs.departmentForm.resetFields()
      this.departmentForm = {
        name: '',
        manager: '',
        code: '',
        introduce: '',
        pid: '',
        id: ''
      }
    },
    // 删除部门
    delDepar(id) {
      this.$confirm('是否确认删除此部门?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delDepartments({ id })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getDepartment()
        })
        .catch(() => {})
    },
    // 新增部门
    submitForm() {
      this.$refs.departmentForm.validate(async valid => {
        if (valid) {
          // 判断是编辑还是新增
          if (this.departmentForm.id) {
            console.log(this.departmentForm.id)
            await updDepartments(this.departmentForm)
            this.$message.success('编辑成功')
          } else {
            await addDepartments(this.departmentForm)
            this.$message.success('新增成功')
          }

          this.dialogFormVisible = false
          this.getDepartment()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获得指定部门信息
    async getDeparById(id) {
      const res = await getDepartmentById({ id })
      this.departmentForm = res
      this.dialogFormVisible = true
    }
  }
}
</script>

<style>
.app-main {
  background-color: #ebedf0;
}
.el-tabs__active-bar {
  background-color: #00a6a6;
}

.el-divider--horizontal {
  margin: 0 0 10px 0;
}
.el-button {
  color: #00a6a6;
}
li.el-select-dropdown__item.selected {
  color: #00a6a6;
}
.el-button--primary {
  background-color: #00a6a6 !important;
  color: #fff;
}
</style>
<style lang="scss">
.departments {
  &-container {
    padding: 50px 15px 40px 60px;
    background-color: #fff;
    border-radius: 5px;
    .el-button {
      color: #fff;
    }
    .el-button--default {
      color: #00a6a6;
    }
    .el-button--primary {
      background-color: #00a6a6;
    }

    .el-message-box__btns {
      .el-button--primary {
        background-color: #00a6a6;
      }
    }
    .el-input__inner:focus {
      border-color: #00a6a6 !important;
    }

    .el-dialog__header {
      background-color: #00a6a6;
    }
    .el-dialog__title,
    .el-dialog__close {
      color: #fff;
    }
    .el-dialog__close {
      color: #fff;
      display: none;
    }
    .el-tabs__item.is-active {
      color: #00a6a6;
    }

    .tree-card {
      padding: 0 70px;
      font-size: 14px;
      box-shadow: 0 0 0 0;
      border: none;

      .card-title {
        font-weight: normal;
        svg {
          font-size: 16px;
        }
        .title {
          font-weight: 600;
          margin-left: 5px;
        }
      }
      .el-row {
        width: 100%;
      }
      .el-dropdown {
        color: #303133;
      }
      .el-col-4 {
        text-align: right;
      }
    }
  }
}
</style>
